#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This's JDBC Util
# -- MySQL
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2018年2月1日 11:40:49
# ----------------------------------------------------------
import pymysql as mysql
from core.app import LOG, SysEnum
from core.utils import read_config


def mysql_connect(db="mysql"):
    """
        Mysql Connect

        :param str db: Databases source
        :return: Mysql connect
        :rtype: object
    """
    try:
        yml = read_config.read_yml(SysEnum.DB_PATH.value)
        mysql_db = mysql.connect(host=yml[db]["host"], user=yml[db]["user"], password=yml[db]["password"],
                                 db=yml[db]["database"], charset=yml[db]["charset"])
        LOG.info("[{}] 数据库连接成功 ...".format(yml[db]["database"]))
        return mysql_db
    except Exception as e:
        LOG.error("[{}] 数据库连接失败：{}".format(yml[db]["database"], e))


def mysql_execute(sql, handle=None, db=None, args=None):
    """
        Mysql Execute

        :param str sql: Execute sql statement.
        :param handle: It's insert, delete, update or select.
        :type handle: str or None
        :param str db: Databases source
        :param list args: Sequence of sequences or mappings.  It is used as parameter.
        :return: Execute result
        :rtype: object
    """
    try:
        if db:
            mysql_db = mysql_connect(db)
        else:
            mysql_db = mysql_connect()
        if mysql_db is None:
            return None
        cursor = mysql_db.cursor()
        LOG.info("Execute sql: {}".format(sql))
        if "select" == handle:
            cursor.execute(sql)
            result = cursor.fetchall()
            return result
        else:
            if not args:
                return 0
            result = cursor.executemany(sql, args)
            mysql_db.commit()
            return result
    except Exception as e:
        LOG.error("操作失败：{}".format(e))
        mysql_db.rollback()
    finally:
        mysql_close(mysql_db)


def mysql_close(mysql_db):
    """
        Mysql Close

        :param object mysql_db: Mysql connect to close.
    """
    if mysql_db:
        mysql_db.close()
